package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleRelationServiceimpl implements ApArticleRelationService {
    @Resource
    ApBehaviorEntryService apBehaviorEntryService;

    @Resource
    ApLikesBehaviorService apLikesBehaviorService;

    @Resource
    ApUnlikesBehaviorService apUnlikesBehaviorService;

    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null || dto.getEntryId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApBehaviorEntry apBehaviorEntry;
        //查询行为实体是否存在
        if (dto.getType().intValue()==1) {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(), null);
        } else {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEntryId());
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("islike", false);
        map.put("isunlike", false);
        map.put("entryId", dto.getEntryId());

        if (apBehaviorEntry == null) {

            return map;
        }

        //查询喜欢数据
        ApLikesBehavior apLikesBehavior = apLikesBehaviorService.getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId()).eq(ApLikesBehavior::getArticleId, dto.getArticleId()));

        if (apLikesBehavior != null) {
            map.put("islike", true);

        }

        //查询不喜欢数据
        ApUnlikesBehavior apUnlikesBehavior = apUnlikesBehaviorService.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()).eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));

        if (apUnlikesBehavior != null) {
            map.put("isunlike", true);

        }

        // {"islike":true,"isunlike":false,"entryId",1}

        return map;
    }
}
